package cn.bone.base.interceptor;


import cn.bone.base.auth.JWTFactory;
import cn.bone.base.auth.JWTInfo;
import cn.bone.base.exception.NoTokenException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private JWTFactory jwtFactory;



    private static Logger logger = LoggerFactory.getLogger("auth");
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String authorization = request.getHeader("Authorization");
        if(StringUtils.isEmpty(authorization)){
            authorization = request.getParameter("Authorization");
        }
        if(StringUtils.isEmpty(authorization)){
            throw new NoTokenException();
        }
        JWTInfo jwtInfo = jwtFactory.validateAndGet(authorization);

        //将用户的jwtInfo保存到当前线程中
        JWTInfo.set(jwtInfo);
        return true;
    }

}
